package pl.edu.agh.ki.ewywiadowka.client.windows.secretary;

import java.util.LinkedList;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratedTabPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SourcesTabEvents;
import com.google.gwt.user.client.ui.TabBar;
import com.google.gwt.user.client.ui.TabListener;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.datepicker.client.DateBox;

import pl.edu.agh.ki.ewywiadowka.client.Const;
import pl.edu.agh.ki.ewywiadowka.client.EWywiadowka;
import pl.edu.agh.ki.ewywiadowka.client.Const.Error.AttendantRegisterMsg;
import pl.edu.agh.ki.ewywiadowka.client.Const.Error.StudentRegisterMsg;
import pl.edu.agh.ki.ewywiadowka.client.dto.AttendantDTO;
import pl.edu.agh.ki.ewywiadowka.client.dto.ClassDTO;
import pl.edu.agh.ki.ewywiadowka.client.dto.StudentDTO;
import pl.edu.agh.ki.ewywiadowka.client.windows.GenericWindow;

public class RegisterStudentAttendantWindow extends GenericWindow implements
		ClickHandler {

	private VerticalPanel _verticalPanel = new VerticalPanel();

	private DecoratedTabPanel _tabPanel = new DecoratedTabPanel();

	private ScrollPanel _mainPanel = new ScrollPanel();

	private VerticalPanel _existingAttendantPanel = new VerticalPanel();
	private VerticalPanel _newAttendantPanel = new VerticalPanel();
	private TextBox _existingAttendantTextBox = new TextBox();
	public ListBox _existingAttendantListBox = new ListBox(true);

	private Grid _studentFormular = null;
	private Grid _attendantFormular = null;

	public int _tabSelectedNumber = 0;

	private String[] _studentFields = { "Imię", "Nazwisko",
			"Numer legitymacji", "Adres", "Data urodzenia",
			"Miejsce urodzenia", "Klasa" };
	private String[] _attendantFields = { "Imię", "Nazwisko", "Adres",
			"Telefon", "Zaklad pracy", "Login", "Haslo" };

	public TextBox _nameTextBox = new TextBox();
	public TextBox _surnameTextBox = new TextBox();
	public TextBox _numberTextBox = new TextBox();
	public TextBox _addressTextBox = new TextBox();
	public DateBox _birthTextBox = new DateBox();
	public TextBox _birthPlaceTextBox = new TextBox();
	public ListBox _classTextBox = new ListBox();

	public TextBox _attendantNameTextBox = new TextBox();
	public TextBox _attendantSurnameTextBox = new TextBox();
	public TextBox _attendantAddressTextBox = new TextBox();
	public TextBox _attendantTelephoneTextBox = new TextBox();
	public TextBox _attendantWorkTextBox = new TextBox();

	public TextBox _attendantLoginTextBox = new TextBox();
	public TextBox _attendantPassTextBox = new TextBox();

	public Button _okButton = new Button("Dodaj ucznia");
	public Button _newAttendantButton = new Button("Dodaj opiekuna");

	public LinkedList<ClassDTO> _classes = null;

	public LinkedList<AttendantDTO> _attendants;

	public RegisterStudentAttendantWindow(EWywiadowka wywiadowka) {
		super(wywiadowka);

		_studentFormular = new Grid(_studentFields.length, 2);
		for (int i = 0; i < _studentFields.length; i++)
			_studentFormular.setWidget(i, 0, new Label(_studentFields[i]));

		_attendantFormular = new Grid(_attendantFields.length, 2);
		for (int i = 0; i < _attendantFields.length; i++)
			_attendantFormular.setWidget(i, 0, new Label(_attendantFields[i]));

		int j = 0;
		_studentFormular.setWidget(j++, 1, _surnameTextBox);
		_studentFormular.setWidget(j++, 1, _nameTextBox);
		_studentFormular.setWidget(j++, 1, _numberTextBox);
		_studentFormular.setWidget(j++, 1, _addressTextBox);
		_studentFormular.setWidget(j++, 1, _birthTextBox);
		_studentFormular.setWidget(j++, 1, _birthPlaceTextBox);
		_studentFormular.setWidget(j++, 1, _classTextBox);

		j = 0;
		_attendantFormular.setWidget(j++, 1, _attendantSurnameTextBox);
		_attendantFormular.setWidget(j++, 1, _attendantNameTextBox);
		_attendantFormular.setWidget(j++, 1, _attendantAddressTextBox);
		_attendantFormular.setWidget(j++, 1, _attendantTelephoneTextBox);
		_attendantFormular.setWidget(j++, 1, _attendantWorkTextBox);
		_attendantFormular.setWidget(j++, 1, _attendantLoginTextBox);
		_attendantFormular.setWidget(j++, 1, _attendantPassTextBox);

		// tutaj feature, żeby filtrowal liste opiekunow
		// _existingAttendantTextBox.

		// _existingAttendantPanel.add(_existingAttendantTextBox);

		_existingAttendantListBox.setVisibleItemCount(10);
		_existingAttendantPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		_existingAttendantPanel.add(_existingAttendantListBox);

		_studentFormular.setBorderWidth(2);
		_attendantFormular.setBorderWidth(2);

		_classTextBox.setVisibleItemCount(5);

		_okButton.addClickHandler(this);

		_verticalPanel
				.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

		_verticalPanel.add(new Label("Dane ucznia"));
		_verticalPanel.add(_studentFormular);

		_verticalPanel.add(new Label("Dane opiekuna"));

		_tabPanel.setAnimationEnabled(true);
		_tabPanel.addTabListener(new TabListener() {

			@Override
			public boolean onBeforeTabSelected(SourcesTabEvents sender,
					int tabIndex) {
				return true;
			}

			@Override
			public void onTabSelected(SourcesTabEvents sender, int tabIndex) {
				_tabSelectedNumber = tabIndex;
			}

		});

		// tutaj SKONCZYLES, zrobienie dodawania opiekuna!!!
		// _newAttendantVerticalPanel.add()

		_newAttendantButton.addClickHandler(this);

		_newAttendantPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		_newAttendantPanel.add(_attendantFormular);
		_newAttendantPanel.add(_newAttendantButton);

		_tabPanel.add(_existingAttendantPanel, "Istniejacy w systemie");
		_tabPanel.add(_newAttendantPanel, "Utworz nowego opiekuna");
		_tabPanel.selectTab(1);

		_verticalPanel.add(_tabPanel);
		_verticalPanel.add(_okButton);

		_mainPanel.add(_verticalPanel);

		this.initWidget(_mainPanel);

		Const.eWywiadowkaService
				.getClasses(new AsyncCallback<LinkedList<ClassDTO>>() {

					@Override
					public void onFailure(Throwable caught) {
						Window.alert(caught.getMessage());
					}

					@Override
					public void onSuccess(LinkedList<ClassDTO> result) {
						_classes = result;
						for (ClassDTO clas : result)
							_classTextBox.addItem(clas.toString());

						_classTextBox.setSelectedIndex(0);
					}

				});

		Const.eWywiadowkaService
				.getAttendants(new AsyncCallback<LinkedList<AttendantDTO>>() {

					@Override
					public void onFailure(Throwable caught) {
						Window.alert(caught.getMessage());
					}

					@Override
					public void onSuccess(LinkedList<AttendantDTO> result) {
						_attendants = result;
						for (AttendantDTO attendant : _attendants)
							_existingAttendantListBox.addItem(attendant
									.toString());
						_existingAttendantListBox.setSelectedIndex(0);
					}

				});

	}

	public Const.FormularMessages verifyFormular() {

		if (_surnameTextBox.getText().length() == 0)
			return Const.FormularMessages.WRONG_SURNAME;
		if (_nameTextBox.getText().length() == 0)
			return Const.FormularMessages.WRONG_NAME;
		try {
			if (_numberTextBox.getText().length() == 0)
				return Const.FormularMessages.WRONG_NUMBER;
			Integer.parseInt(_numberTextBox.getText());
		} catch (NumberFormatException e) {
			return Const.FormularMessages.WRONG_NUMBER;
		}
		if (_addressTextBox.getText().length() == 0)
			return Const.FormularMessages.WRONG_ADDRESS;
		if (_birthTextBox.getValue() == null)
			return Const.FormularMessages.WRONG_BIRTH_DATE;
		if (_birthPlaceTextBox.getText().length() == 0)
			return Const.FormularMessages.WRONG_BIRTH_PLACE;

		if (_tabSelectedNumber == 0) {
			if (_existingAttendantListBox.getItemCount() == 0)
				return Const.FormularMessages.WRONG_ATTENDANT;
		}

		return Const.FormularMessages.OK;
	}

	public Const.FormularMessages verifyAttendantFormular() {
		if (_tabSelectedNumber == 1) {
			if (_attendantSurnameTextBox.getText().length() == 0)
				return Const.FormularMessages.WRONG_ATTENDANT_SURNAME;
			if (_attendantNameTextBox.getText().length() == 0)
				return Const.FormularMessages.WRONG_ATTENDANT_NAME;
			if (_attendantAddressTextBox.getText().length() == 0)
				return Const.FormularMessages.WRONG_ATTENDANT_ADDRESS;
			try {
				if (_attendantTelephoneTextBox.getText().length() == 0)
					return Const.FormularMessages.WRONG_ATTENDANT_PHONE;
				Integer.parseInt(_attendantTelephoneTextBox.getText());
			} catch (NumberFormatException e) {
				return Const.FormularMessages.WRONG_ATTENDANT_PHONE;
			}

			if (_attendantLoginTextBox.getText().length() == 0)
				return Const.FormularMessages.WRONG_LOGIN;

			if (_attendantPassTextBox.getText().length() == 0)
				return Const.FormularMessages.WRONG_PASS;
		}
		return Const.FormularMessages.OK;
	}

	public void attendantRegister() {
		AttendantDTO attendant = new AttendantDTO(null, _attendantNameTextBox
				.getText(), _attendantSurnameTextBox.getText(),
				_attendantAddressTextBox.getText(), _attendantTelephoneTextBox
						.getText(), _attendantWorkTextBox.getText(), null, null);
		
		Const.eWywiadowkaService.registerAttendant(attendant, new AsyncCallback<AttendantRegisterMsg>() {

			@Override
			public void onFailure(Throwable caught) {
				Window.alert(caught.getMessage());
			}

			@Override
			public void onSuccess(AttendantRegisterMsg result) {
				if (result == AttendantRegisterMsg.OK) {
					Const.eWywiadowkaService.getAttendants(new AsyncCallback<LinkedList<AttendantDTO>>() {

						@Override
						public void onFailure(Throwable caught) {
							Window.alert(caught.getMessage());
						}

						@Override
						public void onSuccess(LinkedList<AttendantDTO> result) {
							_attendants = result;
							_existingAttendantListBox.clear();
							for (AttendantDTO attendant : _attendants)
								_existingAttendantListBox.addItem(attendant
										.toString());
							_existingAttendantListBox.setSelectedIndex(0);
						}
						
					});
				}
				Window.alert(result.toString());
				
			}
			
		});
	}

	private void studentRegister() {

		ClassDTO clas = _classes.get(_classTextBox.getSelectedIndex());
		LinkedList<AttendantDTO> attendants = new LinkedList<AttendantDTO>();

		if (_tabSelectedNumber == 1) {
			Window
					.alert("Uzyj zakladki \"Isniejacy w systemie\" dla wyboru opiekunow ucznia");
			return;
		} else
			for (int i = 0; i < _attendants.size(); i++)
				if (_existingAttendantListBox.isItemSelected(i))
					attendants.add(_attendants.get(i));

		StudentDTO student = new StudentDTO(_surnameTextBox.getText(),
				_nameTextBox.getText(), Integer.parseInt(_numberTextBox
						.getText()), _addressTextBox.getText(), _birthTextBox
						.getValue(), _birthPlaceTextBox.getText(), attendants,
				clas);

		Const.eWywiadowkaService.registerStudent(student,
				new AsyncCallback<StudentRegisterMsg>() {

					@Override
					public void onFailure(Throwable caught) {
						Window.alert(caught.getMessage());
					}

					@Override
					public void onSuccess(StudentRegisterMsg result) {
						Window.alert(result.toString());
					}

				});
	}

	public void onClick(ClickEvent event) {
		if (event.getSource() == _okButton) {
			Const.FormularMessages msg = null;
			if ((msg = verifyFormular()) == Const.FormularMessages.OK)
				studentRegister();
			else
				Window.alert(msg.toString());
		} else if (event.getSource() == _newAttendantButton) {
			Const.FormularMessages msg = null;
			if ((msg = verifyAttendantFormular()) == Const.FormularMessages.OK)
				attendantRegister();
			else
				Window.alert(msg.toString());
		}

	}
}
